package com.lyw.i13ForkJoinFrameWork;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;

/**
 * 1、Fork/Join 框架
 *    把一个任务拆分成多个子任务进行处理，最后将子任务结果合并成最后的结果，并进行输出
 *    - Fork 把复杂任务进行拆分，化大为小
 *    - Join 把拆分的任务结果合并
 *
 *
 * @author lyw
 * @Date 2023/7/11-下午10:49
 */
class MyTask extends RecursiveTask<Integer> {
  private Integer result = 0;
  private Integer begin;
  private Integer end;
  public final int VALUE = 10;

  public MyTask(Integer begin, Integer end) {
    this.begin = begin;
    this.end = end;
  }

  @Override
  protected Integer compute() {
    if ((end - begin) <= VALUE) {
      for (int i = begin; i <= end; i++) {
        result += i;
      }

      return result;
    } else {

      int middle = (end + begin) / 2;
      MyTask myTask01 = new MyTask(begin, middle);
      MyTask myTask02 = new MyTask(middle + 1, end);
      myTask01.fork();
      myTask02.fork();
      return myTask01.join() + myTask02.join();
    }
  }
}
public class ForkJoinFrameWorkDemo {

  public static void main(String[] args) throws ExecutionException, InterruptedException {
    MyTask task = new MyTask(0, 100);
    // 创建拆分合并池
    ForkJoinPool pool = new ForkJoinPool();
    ForkJoinTask<Integer> forkJoinTask = pool.submit(task);
    System.out.println(forkJoinTask.get());
    pool.shutdown();
  }
}
